import { openDB } from 'idb';

const DB_NAME = 'mechat-db';
const DB_VERSION = 2;
const STORE_NAMES = {
  USER: 'user',
  CONTACTS: 'contacts',
  MESSAGES: 'messages',
  ADRESSBOOK:'addressbook',
  SCHEDULEDTASKS: 'scheduledTasks'
};

const dbPromise = openDB(DB_NAME, DB_VERSION, {
  upgrade(db, oldVersion, newVersion) {
    // 创建对象存储空间
    if (!db.objectStoreNames.contains(STORE_NAMES.USER)) {
      db.createObjectStore(STORE_NAMES.USER, { keyPath: 'id' });
    }
    if (!db.objectStoreNames.contains(STORE_NAMES.CONTACTS)) {
      db.createObjectStore(STORE_NAMES.CONTACTS, { keyPath: 'id' });
    }
    if (!db.objectStoreNames.contains(STORE_NAMES.MESSAGES)) {
      db.createObjectStore(STORE_NAMES.MESSAGES, { keyPath: 'id' });
    }
    if (!db.objectStoreNames.contains(STORE_NAMES.ADRESSBOOK)) {
      db.createObjectStore(STORE_NAMES.ADRESSBOOK, { keyPath: 'id' });
    }
    // 版本2新增定时任务存储空间
    if (oldVersion < 2) {
      if (!db.objectStoreNames.contains(STORE_NAMES.SCHEDULEDTASKS)) {
        db.createObjectStore(STORE_NAMES.SCHEDULEDTASKS, { keyPath: 'id' });
      }
      
      // 数据迁移：将原MESSAGES store中的定时任务数据迁移到新的SCHEDULEDTASKS store
      const migrateScheduledTasks = async () => {
        try {
          // 获取旧存储中的定时任务数据
          const tx = db.transaction([STORE_NAMES.MESSAGES, STORE_NAMES.SCHEDULEDTASKS], 'readwrite');
          const oldStore = tx.objectStore(STORE_NAMES.MESSAGES);
          const newStore = tx.objectStore(STORE_NAMES.SCHEDULEDTASKS);
          
          // 查询旧数据
          const scheduledTasksData = await oldStore.get('scheduledTasks');
          
          // 如果存在数据，则迁移到新store
          if (scheduledTasksData && scheduledTasksData.data) {
            await newStore.put(scheduledTasksData);
            console.log('定时任务数据已从MESSAGES迁移到SCHEDULEDTASKS');
          }
          
          await tx.done;
        } catch (error) {
          console.error('迁移定时任务数据失败:', error);
        }
      };
      
      // 执行数据迁移
      migrateScheduledTasks();
    }
  }
  }
);

export const dbService = {
  // 获取单个数据
  async get(storeName, key) {
    if (!storeName || !key) {
      throw new Error('storeName和key参数不能为空');
    }
    return (await dbPromise).get(storeName, key);
  },
  
  // 获取所有数据
  async getAll(storeName) {
    return (await dbPromise).getAll(storeName);
  },
  
  // 添加或更新数据
  async set(storeName, value) {
    if (!storeName || !value) {
      throw new Error('storeName和value参数不能为空');
    }
    return (await dbPromise).put(storeName, value);
  },
  
  // 删除数据
  async delete(storeName, key) {
    if (!storeName || !key) {
      throw new Error('storeName和key参数不能为空');
    }
    return (await dbPromise).delete(storeName, key);
  },
  
  // 清空存储空间
  async clear(storeName) {
    if (!storeName) {
      throw new Error('storeName参数不能为空');
    }
    return (await dbPromise).clear(storeName);
  },
  
  // 获取存储空间名称
  getStoreNames() {
    return STORE_NAMES;
  }
};